import {
  storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import {
  queryDiscount,
  queryMemberCouponDiscount
} from "@src/api/order";
import base from "@src/store/base";
import router from "@src/router";
import {
  discountMd5
} from "@src/common/discountUtils";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  data: {
    selected: null,
    discountInfo: {},
    discountList: [],
    type: null,
  },
  methods: {
    onLoad(options) {
      let {
        shopId,
        totalFee,
        selectItem,
        orderType,
        type
      } = options;
      this.setData({
        shopId,
        totalFee,
        selectItem,
        orderType,
        type
      });
      this.fetchData();
    },
    fetchData() {
      let data = {
        orderType: this.data.orderType,
        shopId: this.data.shopId,
        tradeFee: this.data.totalFee
      }
      let callFun = queryDiscount;

      if (this.data.type && this.data.type === 'memberCoupon') {
        callFun = queryMemberCouponDiscount
      }

      callFun(data).then(res => {
        if (res.code === 0) {
          let discountList = res.data
          for (let i = 0; i < discountList.length; i++) {
            let discountInfo = discountList[i];
            if (this.data.selectItem && this.data.selectItem === discountMd5(discountInfo)) {
              this.setData({
                discountInfo: discountInfo,
                selected: i,
                discountList: discountList
              })
              return;
            }
          }
          this.setData({
            selected: null,
            discountInfo: null,
            discountList: discountList
          })
        }
      })
    },
    handleSelect(e) {
      let index = e.currentTarget.dataset.index;
      if (index === this.data.selected) {
        this.setData({
          selected: null,
          discountInfo: null
        });
        return;
      }
      this.setData({
        selected: index,
        discountInfo: this.data.discountList[index]
      });
    },
    handleConfirm(e) {
      let {
        currentTarget: {
          dataset: {
            type
          }
        }
      } = e
      if (type) {
        this.setData({
          selected: null,
          discountInfo: null
        });
      }
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel) {
        eventChannel.emit('change', this.data.discountInfo);
      }
      router.back()
    }
  }
})